// 基本信息
import { getDeptList } from "@/api/modules/dept";
import { getNotifyTemplateList } from "@/api/modules/notification";
import DialogBox from "@/components/DialogBox";
import UserSelectDialog from "./userSelectDialog.vue";
import DeptTree from "@/components/Sansan/DeptTree";
import { ElForm, ElMessage } from "element-plus";
import { getCurrentInstance, defineComponent, PropType, ComponentInternalInstance } from "vue";
import "./mould-detail.scss";
import { getUserList } from "@/api/modules/user";
import SelectDeptList from "@/components/Sansan/SelectDeptList";
import TagInput from "@/components/Tags/TagInput";
import { notifyUserType } from "@/utils/constants";
import { getDictList } from "@/utils/cacheUtil";
import { getDeviceAlarmConfigList } from "@/api/modules/iot/alarm";
import { AuthStore } from "@/stores/modules/auth";
interface DeviceForm {
	[key: string]: any;
}
export default defineComponent({
	props: {
		width: String,
		title: String,
		detail: {
			type: Object as PropType<DeviceForm>,
			default() {
				return {};
			}
		}
	},
	emits: ["submit"],
	setup(props, { emit, attrs }) {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		type FormInstance = InstanceType<typeof ElForm>;
		const formRef = ref<FormInstance>();
		const formRule = reactive({
			name: [{ required: true, message: "请输入模版名称", trigger: "change" }],
			templateId: [{ required: true, message: "请选择通知模板", trigger: "change" }],
			deptId: [{ required: true, message: "请选择分组", trigger: "change" }]
		});
		const defaultData = reactive({
			typeSlt: [] as any,
			alarmSlt: [] as any
		});
		const validData = () => {
			formRef.value?.validate(valid => {
				if (valid) {
					if (props.detail.sendTargetType == "1") {
						props.detail.sendTarget = assignGroup.value.map((item: any) => item.id).toString();
					} else if (props.detail.sendTargetType == notifyUserType.systemUser) {
						props.detail.sendTarget = userList.value.map((item: any) => item.id).toString();
					} else if (props.detail.sendTargetType == notifyUserType.custUser) {
						sendTarget.value.mobile = sendTarget.value.mobile.toString().replaceAll(",", ";");
						sendTarget.value.email = sendTarget.value.email.toString().replaceAll(",", ";");
						props.detail.sendTarget = sendTarget.value.email || sendTarget.value.mobile ? JSON.stringify(sendTarget.value) : "";
					}
					if (!props.detail.sendTarget) {
						ElMessage.error("请选择通知对象");
						return;
					}
					if (!props.detail.source) {
						typeData.value.alarmType = "";
						typeData.value.alarmLevel = "";
						props.detail.deptId = "";
					}
					props.detail.type = JSON.stringify(typeData.value);
					props.detail.source = props.detail.source ? "1" : "0";

					emit("submit");
				}
			});
		};
		const deptList = ref();
		onMounted(async () => {
			getDictType();
			getAlarmList();
			let res = await getDeptList();
			deptList.value = res.result.records.children;
			initTemplateList();
			if (props.detail.id) {
				if (props.detail.templateId) {
					let obj = JSON.parse(props.detail.templateId);
					//初始化通知模版选择
					templateSelectList.value = Object.keys(obj).map((item: any) => {
						return { id: obj[item], type: item };
					});
				}
				if (props.detail.sendTargetType == "1") {
					assignGroup.value = props.detail.sendTarget.split(",").map((item: any) => {
						return { id: item };
					});
				} else if (props.detail.sendTargetType == notifyUserType.systemUser) {
					initUser();
				} else if (props.detail.sendTargetType == notifyUserType.custUser && JSON.parse(props.detail.sendTarget)) {
					sendTarget.value.email =
						JSON.parse(props.detail.sendTarget).email && JSON.parse(props.detail.sendTarget).email.split(";");
					sendTarget.value.mobile =
						JSON.parse(props.detail.sendTarget).mobile && JSON.parse(props.detail.sendTarget).mobile.split(";");
				}
				props.detail.source = props.detail.source == 1 ? true : false;
				if (props.detail.type) {
					try {
						typeData.value.alarmLevel = JSON.parse(props.detail.type).alarmLevel;
						typeData.value.alarmType = JSON.parse(props.detail.type).alarmType;
					} catch {}
				}
			} else {
				props.detail.status = "1";
				props.detail.source = true;
				props.detail.sendTargetType = notifyUserType.systemUser;
			}
		});
		//初始化消息模版
		const initTemplateList = async () => {
			let { result } = await getNotifyTemplateList({});
			result.map((item: any) => {
				if (item.type == "1") {
					options.value[0].options = [...options.value[0].options, item];
				} else if (item.type == "2") {
					options.value[1].options = [...options.value[1].options, item];
				}
			});
		};
		const initUser = async () => {
			let { result } = await getUserList({ id: props.detail.sendTarget as string, self: 1 });
			userSelect(result.records);
		};
		const options = ref<any>([
			{ label: "短信", options: [] },
			{ label: "邮件", options: [] }
		]);
		const templateSelectEl = ref();
		//转换通知模版选择的数据
		const templateIdChange = (val: any) => {
			let currentSelect = val[val.length - 1];
			if (currentSelect) {
				templateSelectList.value = val.filter((item: any) => {
					return (item.type == currentSelect.type && item.id == currentSelect.id) || item.type != currentSelect.type;
				});
				let obj: any = {};
				templateSelectList.value.map((item: any) => {
					obj[item.type] = item.id;
				});
				props.detail.templateId = JSON.stringify(obj);
			} else {
				props.detail.templateId = "";
			}
			templateSelectEl.value.blur();
		};

		//通知对象按分组树选择数据处理
		const submitAssignGroup = (val: any) => {
			assignGroup.value = val.checked;
		};
		const assignGroup = ref([]);
		//选择的通知模版
		const templateSelectList = ref<any>([]);
		const sendTarget = ref({ mobile: "", email: "" });
		const typeData = ref({ alarmLevel: "", alarmType: "" });
		const userList = ref([]);
		const drawerVisible = ref(false);

		const userSelect = (val: any) => {
			userList.value = val;
			// userList.value = val.map((item: any) => {
			// 	return item.username;
			// });
		};
		// 获取告警级别
		const getDictType = async () => {
			const list = await getDictList("warning_level");
			defaultData.typeSlt = list;
		};
		const authStore = AuthStore();
		// 获取告警类型
		const getAlarmList = (e?: any) => {
			getDeviceAlarmConfigList({
				pageSize: 999999,
				pageIndex: 1,
				prodOrDev: "device",
				deptId: e ? authStore.getDeptIdChild(e.node) : ""
			}).then((res: any) => {
				const list = [] as any;
				if (res.code == 200 && res.result?.records) {
					res.result?.records.map((item: any) => {
						if (item.warning && item.warning.length) {
							item.warning.map((info: any) => {
								if (!list.includes(info.alarmType)) {
									list.push(info.alarmType);
								}
							});
						}
					});
				}
				defaultData.alarmSlt = list;
			});
		};
		return () => {
			return (
				<DialogBox {...attrs} width={props.width || "700px"} title={props.title} onConfirm={validData}>
					<div style="max-height: 80vh;overflow-y: auto;">
						<el-form model={props.detail} ref={formRef} rules={formRule} size="large" label-width="110">
							<el-form-item label={proxy?.$t("notify_configdetail.form_label.status")} prop="status">
								<el-radio-group v-model={props.detail.status}>
									<el-radio label="1">{proxy?.$t("notify_configdetail.radio.enable")}</el-radio>
									<el-radio label="0">{proxy?.$t("notify_configdetail.radio.deactivate")}</el-radio>
								</el-radio-group>
							</el-form-item>
							<el-form-item label={proxy?.$t("notify_configdetail.form_label.source")} prop="status">
								<el-checkbox v-model={props.detail.source}>{proxy?.$t("notify_configdetail.checkbox.yes")}</el-checkbox>
							</el-form-item>
							{props.detail.source ? (
								<>
									<el-form-item
										label={proxy?.$t("notify_configdetail.form_label.deptid")}
										prop="deptId"
										v-slots={{
											label: () => {
												return (
													<>
														<el-tooltip show-after={500} content={proxy?.$t("notify_configdetail.tooltip.deptid")}>
															<span class="iconfont iconinfo pr-2" />
														</el-tooltip>
														<span>{proxy?.$t("notify_configdetail.form_label.deptid")}</span>
													</>
												);
											}
										}}
									>
										<SelectDeptList
											detail={props.detail}
											onChange={(e: any) => {
												typeData.value.alarmType = "";
												getAlarmList(e);
											}}
										/>
									</el-form-item>
									<el-form-item label={proxy?.$t("notify_configdetail.form_label.alarm_type")} prop="alarmType">
										<el-select
											v-model={typeData.value.alarmType}
											clearable
											placeholder={proxy?.$t("notify_configdetail.select.placeholder")}
											class="w-full"
											value-key="id"
										>
											{defaultData.alarmSlt.map((item: any, index: number) => {
												return <el-option key={index} label={item} value={item}></el-option>;
											})}
										</el-select>
									</el-form-item>
									<el-form-item label={proxy?.$t("notify_configdetail.form_label.level")} prop="alarmLevel">
										<el-select
											v-model={typeData.value.alarmLevel}
											clearable
											placeholder={proxy?.$t("notify_configdetail.select.placeholder")}
											class="w-full"
											value-key="id"
										>
											{defaultData.typeSlt.map((item: any) => {
												return <el-option key={item.key} label={item.label} value={item.key}></el-option>;
											})}
										</el-select>
									</el-form-item>
								</>
							) : null}
							<el-form-item label={proxy?.$t("notify_configdetail.form_label.name")} prop="name">
								<el-input v-model={props.detail.name} placeholder={proxy?.$t("notify_configdetail.name.placeholder")} />
							</el-form-item>
							<el-form-item label={proxy?.$t("notify_configdetail.form_label.template")} prop="templateId">
								<el-select
									v-model={templateSelectList.value}
									placeholder={proxy?.$t("notify_configdetail.select.placeholder")}
									multiple
									class="w-full"
									onChange={templateIdChange}
									value-key="id"
									clearable
									ref={templateSelectEl}
								>
									{options.value.map((group: any) => {
										return (
											<el-option-group key={group.label} label={group.label}>
												{group.options.map((item: any) => {
													return <el-option key={item.id} label={item.name} value={item}></el-option>;
												})}
											</el-option-group>
										);
									})}
								</el-select>
							</el-form-item>
							<el-form-item label={proxy?.$t("notify_configdetail.form_label.send_target")} prop="sendTargetType">
								<el-radio-group v-model={props.detail.sendTargetType}>
									<el-radio label={notifyUserType.systemUser}>
										{proxy?.$t("notify_configdetail.target_radio.systemuser")}
									</el-radio>
									<el-radio label={notifyUserType.custUser}>{proxy?.$t("notify_configdetail.target_radio.custuser")}</el-radio>
								</el-radio-group>
							</el-form-item>
							{props.detail.sendTargetType == "1" && (
								<DeptTree
									detail={{ deptId: props.detail.sendTarget && props.detail.sendTarget.split(",") }}
									multiple
									onChange={submitAssignGroup}
									class="ml-4"
								/>
							)}
							<UserSelectDialog
								class="dialog-dense"
								v-model:visible={drawerVisible.value}
								onSubmit={userSelect}
								selectDefault={userList.value.map((item: any) => item.id)}
							></UserSelectDialog>
							{props.detail.sendTargetType == notifyUserType.systemUser && (
								<el-form-item label={proxy?.$t("notify_configdetail.form_label.username")}>
									<el-select
										class="w-full "
										v-model={userList.value}
										placeholder={proxy?.$t("notify_configdetail.select_usename.placeholder")}
										multiple
										value-key="id"
										onFocus={() => {
											drawerVisible.value = true;
										}}
									>
										{userList.value.map((item: any) => {
											return <el-option key={item.id} label={item.username} value={item}></el-option>;
										})}
									</el-select>
								</el-form-item>
							)}
							{props.detail.sendTargetType == notifyUserType.custUser && (
								<div>
									<el-form-item label="邮件">
										<TagInput v-model={sendTarget.value.email} />
									</el-form-item>
									<el-form-item label="手机号">
										<TagInput v-model={sendTarget.value.mobile} />
									</el-form-item>
								</div>
							)}
						</el-form>
					</div>
				</DialogBox>
			);
		};
	}
});
